import store from '@/store'
import api from '@/config'

export const hasWebAudioAPI = {
  data: true
}

export const music = {}
;(() => {
  const context = wx.createWebAudioContext()

  const loadAudio = (url) => {
    return new Promise((resolve) => {
      wx.request({
        url,
        responseType: 'arraybuffer',
        success: res => {
          context.decodeAudioData(res.data, buffer => {
            resolve(buffer)
          }, err => {
            console.error('decodeAudioData fail', err)
            reject()
          })
        },
        fail: res => {
          console.error('request fail', res)
          reject()
        }
      })
    })
  }

  loadAudio(api.base + '/renzhi-admin/file_attached/20230115/f426865bbc354fd686c1e10fd06d2360.mp3').then(buf => {
    // 将拿到的audio解码转为buffer
    const getSource = () => {
      // 创建source源。
      const source = context.createBufferSource()
      source.buffer = buf
      source.connect(context.destination)
      return source
    }

    music.killStart = () => {
      // 游戏开始的音乐只播放一次
      music.start = () => {}
    }

    music.start = () => {
      // 游戏开始
      music.killStart()
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 3.7202, 3.6224)
    }

    music.clear = () => {
      // 消除方块
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 0, 0.7675)
    }

    music.fall = () => {
      // 立即下落
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 1.2558, 0.3546)
    }

    music.gameover = () => {
      // 游戏结束
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 8.1276, 1.1437)
    }

    music.rotate = () => {
      // 旋转
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 2.2471, 0.0807)
    }

    music.move = () => {
      // 移动
      if (!store.state.tetris.music) {
        return
      }
      getSource().start(0, 2.9088, 0.1437)
    }
  },
  error => {
    if (window.console && window.console.error) {
      window.console.error(`音频: ${url} 读取错误`, error)
      hasWebAudioAPI.data = false
    }
  }
  )
})()
